package com.yexiao.cofe.interceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.yexiao.cofe.util.MybatisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;

@Slf4j
public class SqlInterceptor implements InnerInterceptor {

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        log(ms, parameter, boundSql);
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter){
        log(ms, parameter, (BoundSql)null);
    }

    private void log(MappedStatement ms, Object parameter, BoundSql boundSql) {
        try {
            if (boundSql == null) {
                boundSql = ms.getBoundSql(parameter);
            }

            Configuration configuration = ms.getConfiguration();
            String sql = MybatisUtil.getSql(configuration, boundSql);
            log.info(sql);
        } catch (Exception var7) {
            log.error(var7.getMessage(), var7);
        }

    }
}